package com.hspedu.bot.service.impl.user.bot;

import com.hspedu.bot.pojo.Bot;
import com.hspedu.bot.pojo.User;
import com.hspedu.bot.service.user.bot.BotService;
import com.hspedu.bot.service.user.bot.UpdateService;
import com.hspedu.bot.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UpdateServiceImpl implements UpdateService {

    @Autowired
    private BotService botService;

    @Override
    public Map<String, String> update(Map<String, String> data) {

        UsernamePasswordAuthenticationToken authenticationToken
                = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        Integer bot_id = Integer.parseInt(data.get("bot_id"));
        String title = data.get("title");
        String description = data.get("description");
        String content = data.get("content");

        //判断逻辑
        Map<String, String> map = new HashMap<>();
        if (!StringUtils.hasText(title)) {
            map.put("error_message", "标题不能为空");
            return map;
        }

        if (title.length() > 100) {
            map.put("error_message", "标题长度不能大于100");
            return map;
        }

        if (!StringUtils.hasText(description)) {
            description = "这个用户很懒，什么也没留下~";
        }

        if (description.length() > 300) {
            map.put("error_message", "Bot描述的长度不能大于300");
            return map;
        }

        if (!StringUtils.hasText(content)) {
            map.put("error_message", "代码不能为空");
            return map;
        }

        if (content.length() > 10000) {
            map.put("error_message", "代码长度不能超过10000");
            return map;
        }

        //根据bot表的id查询数据
        Bot bot = botService.getById(bot_id);

        //1.bot 不存在
        if (bot == null) {
            map.put("error_message", "Bot不存在或已被删除");
            return map;
        }

        //2.当前user没有权限修改当前bot
        if (bot.getUserId() != user.getId()) {
            map.put("error_message", "没有权限修改该Bot");
            return map;
        }

        //创建一个新对象
        Bot new_bot = new Bot(
                bot.getId(),
                user.getId(),
                title,
                description,
                content,
                bot.getCreatetime(),
                new Date()
        );

        //修改
        botService.updateById(new_bot);
        map.put("error_message", "success");

        return map;
    }
}
